package com.zhida.chatservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhida.chatservice.entity.GroupMessage;
import com.zhida.chatservice.entity.UserMessage;
import com.zhida.chatservice.mapper.GroupMessageMapper;
import com.zhida.chatservice.mapper.UserMessageMapper;
import com.zhida.chatservice.service.IMessageService;
import com.zhida.chatservice.utils.MsgUtil;
import com.zhida.common.context.UserContext;
import com.zhida.common.entity.Result;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.zhida.common.utils.StaticKeyUtil.WS_OFFLINE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ling
 * @since 2024-07-19
 */
@Service
public class MessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage> implements IMessageService {

    @Resource
    RedisTemplate<String,String> redisTemplate;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    UserMessageMapper userMessageMapper;
    @Resource
    GroupMessageMapper groupMessageMapper;

    @Override
    public Result<?> getOfflineMsg() throws JsonProcessingException {
        String username = UserContext.getUser();
//        从缓存中取离线消息
        String offlineMsg = redisTemplate.opsForValue().get(WS_OFFLINE_KEY + username);
        if (offlineMsg==null){
            return Result.successMsg("没有离线消息");
        }
//        从缓存中移除离线消息
        redisTemplate.delete(WS_OFFLINE_KEY + username);
        return Result.success(new ObjectMapper().readValue(offlineMsg, ArrayList.class));
    }

    @Override
    public Result<?> backupUserMessage() {
        long begin = System.currentTimeMillis();
        int effect = 0;
        try {
            List<UserMessage> userMessages = MsgUtil.backupUserMessage(redisTemplate,stringRedisTemplate);
            for (UserMessage userMessage : userMessages) {
                ++effect;
                userMessageMapper.insert(userMessage);
            }
        } catch (JsonProcessingException e){
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        HashMap<String, Object> result = new HashMap<>();
        result.put("count",effect);
        result.put("coast",end-begin + "ms");
        return Result.success(result);
    }

    @Override
    public Result<?> getMessage(String to,Integer current, Integer pageSize) {
        String username = UserContext.getUser();
        Page page = new Page<>(current,pageSize);
        // 使用QueryWrapper构建查询条件 1721379561279
        QueryWrapper<UserMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("message_id","come_from","time","msg").nested(wrapper -> wrapper.eq("username", username).eq("come_from", to))
                .or(wrapper -> wrapper.eq("username", to).eq("come_from", username));
        queryWrapper.orderByDesc("time"); // 按照time字段降序排序

        return Result.success(userMessageMapper.selectMapsPage(page,queryWrapper));
    }

    @Override
    public Result<?> backupGroupMessage() {
        long begin = System.currentTimeMillis();
        int effect = 0;
        try {
            List<GroupMessage> groupMessages = MsgUtil.backupGroupMessage(redisTemplate, stringRedisTemplate);
            for (GroupMessage groupMessage : groupMessages) {
                ++effect;
                groupMessageMapper.insert(groupMessage);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        HashMap<String, Object> result = new HashMap<>();
        result.put("count",effect);
        result.put("coast",end-begin + "ms");
        return Result.success(result);
    }
}
